package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.consts.Const;
import com.example.demo.entity.Comment;
import com.example.demo.entity.User;
import com.example.demo.mapper.CommentMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.param.CommentParam;
import com.example.demo.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CommentServiceImpl implements CommentService {

    @Resource
    private CommentMapper commentMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String, Integer> redisTemplate;

    @Override
    public List<Comment> findCommentByUserId(Long userId, Integer pageNo) {
        QueryWrapper<Comment> wrapper = new QueryWrapper();
        wrapper.eq("user_id",userId).orderByDesc("create_time");
        Page<Comment> page = new Page<>(pageNo, Const.PAGE_SIZE);
        IPage<Comment> commentIPage = commentMapper.selectPage(page, wrapper);
        List<Comment> records = commentIPage.getRecords();
        for (Comment record : records) {
            Integer likeCount = redisTemplate.opsForValue().get(Const.COMMENT_LIKE+"_"+record.getId());
            if(likeCount!=null){
                record.setLikeCount(likeCount);
            }
        }
        return records;
    }

    @Override
    public List<Comment> findPoetryComment(Long poetryId, Integer pageNo) {
        QueryWrapper<Comment> wrapper = new QueryWrapper();
        wrapper.eq("object_id",poetryId).eq("type",Const.POETRY_TYPE).orderByDesc("create_time");
        Page<Comment> page = new Page<>(pageNo, Const.PAGE_SIZE);
        IPage<Comment> commentIPage = commentMapper.selectPage(page, wrapper);
        List<Comment> records = commentIPage.getRecords();
        for (Comment record : records) {
            Integer likeCount = redisTemplate.opsForValue().get(Const.COMMENT_LIKE+"_"+record.getId());
            if(likeCount!=null){
                record.setLikeCount(likeCount);
            }
        }
        return records;
    }

    @Override
    public Integer insertComment(CommentParam commentParam) {
        Long userId = commentParam.getUserId();
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("id",userId);
        User users = userMapper.selectOne(wrapper);
        Comment comment = Comment.builder().avatar(users.getImgUrl()).username(users.getUsername()).build();
        BeanUtils.copyProperties(commentParam,comment);
        return commentMapper.insert(comment);
    }



}
